package cn.sunagy.security.maz.auth.client.interceptor;

import cn.sunagy.maz.core.context.BaseContextHandler;
import cn.sunagy.security.maz.auth.client.config.ServiceAuthConfig;
import cn.sunagy.security.maz.auth.client.config.UserAuthConfig;
import cn.sunagy.security.maz.auth.client.jwt.ServiceAuthUtil;
import cn.sunagy.security.maz.common.constant.ResponseCodeConstants;
import lombok.extern.java.Log;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @desc：#TODO fill me ！
 * @author：三餘無夢生
 * @date：2018/6/2
 * @time：下午2:03
 */
@Component
@Log
public class OkHttpTokenInterceptor implements Interceptor {
    @Autowired
    @Lazy
    private ServiceAuthUtil serviceAuthUtil;
    @Autowired
    @Lazy
    private ServiceAuthConfig serviceAuthConfig;
    @Autowired
    @Lazy
    private UserAuthConfig userAuthConfig;


    @Override
    public Response intercept(Chain chain) throws IOException {
        Request newRequest = chain.request()
                .newBuilder()
                .header(userAuthConfig.getTokenHeader(), BaseContextHandler.getToken())
                .build();
        Response response = chain.proceed(newRequest);
        if(HttpStatus.FORBIDDEN.value()==response.code()){
            if(response.body().string().contains(String.valueOf(ResponseCodeConstants.EX_CLIENT_INVALID_CODE))){
                log.info("Client Token Expire,Retry to request...");
                serviceAuthUtil.refreshClientToken();
                newRequest = chain.request()
                        .newBuilder()
                        .header(userAuthConfig.getTokenHeader(), BaseContextHandler.getToken())
                        .header(serviceAuthConfig.getTokenHeader(),serviceAuthUtil.getClientToken())
                        .build();
                response = chain.proceed(newRequest);
            }
        }
        return response;
    }

}
